package com.towker.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

/**
 * Cookie的常用操作
 * @version
 */
public class MyCookie
{
	private HttpServletResponse response;
	private HttpServletRequest request;

	public MyCookie(PageContext context)
	{
		this.response = (HttpServletResponse) context.getResponse();
		this.request = (HttpServletRequest) context.getRequest();
	}

	/**
	 * 只读cookie的话，response传null即可
	 * @param request
	 * @param response
	 */
	public MyCookie(HttpServletRequest request, HttpServletResponse response)
	{
		this.request = request;
		this.response = response;
	}

	/**
	 * 往客户端写入Cookie 说明:
	 * @param name String
	 * @param value String
	 * @param maxAge(单位秒) 0:删除Cookie -1:页面关闭时删除cookie
	 * @param cookieURI String
	 */
	public void addCookie(String name, String value, int maxAge, String cookieURI)
	{
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(cookieURI);
		response.addCookie(cookie);
	}

	/**
	 * 往客户端写入Cookie 说明: maxAge:(单位秒) 0:删除Cookie -1:页面关闭时删除cookie
	 * @param name String
	 * @param value String
	 * @param maxAge int
	 */
	public void addCookie(String name, String value, int maxAge)
	{
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
	}

	/**
	 * 写入cookie 当页面关闭是删除cookie。
	 * @param name
	 * @param value
	 */
	public void addCookie(String name, String value)
	{
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(-1);
		response.addCookie(cookie);
	}

	/**
	 * 删除cookie
	 * @param name
	 */
	public void delCookie(String name)
	{
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	/**
	 * 根据cookie名称取得值
	 * @param name
	 * @param request
	 * @return
	 */
	public String getValueByName(String name)
	{
		Cookie cookies[] = request.getCookies();
		Cookie sCookie = null;
		String svalue = null;
		String sname = null;
		if (cookies == null)
			return null;
		for (int i = 0; i < cookies.length; i++)
		{
			sCookie = cookies[i];
			sname = sCookie.getName();
			if (sname.equals(name))
			{
				svalue = sCookie.getValue();
				break;
			}
		}
		return svalue;
	}

	/**
	 * 根据Cookie名判断Cookie是否存在.
	 * @param name String
	 * @param context PageContext
	 * @return String
	 */
	public boolean isExistByName(String name)
	{
		Cookie cookies[] = request.getCookies();
		Cookie sCookie = null;
		String sname = null;
		boolean isExist = false;
		if (cookies == null)
			return false;
		for (int i = 0; i < cookies.length; i++)
		{
			sCookie = cookies[i];
			sname = sCookie.getName();
			if (sname.equals(name))
			{
				isExist = true;
				break;
			}
		}
		return isExist;
	}
}
